package com.gzu.finalwork.user.controller;

import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.entity.user.Users;
import com.gzu.finalwork.user.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class UserController {
    @Autowired
    private UserService userService;
    // 用户注册
    @PostMapping("/register")
    public Object register(@RequestBody Users users, HttpSession session) {
        try {
            return AjaxResult.success(userService.register(users,session), "注册成功！");
        }catch (Exception e) {
            return AjaxResult.error(-1,"注册失败，请稍后再试！");
        }
    }
    
    // 用户登录
    @PostMapping("/login")
    public Object login(@RequestParam String username ,@RequestParam String password,@RequestParam String roles, HttpSession session) {
        try {
            Users user = new Users();
            user.setUsername(username);
            user.setPassword(password);
            user.setRoles(roles);
            return AjaxResult.success(userService.login(user, session), "登录成功！");
        }catch (Exception e) {
            return AjaxResult.error(-1,"登录失败，请稍后再试！");
        }
    }
    
    // 获取用户信息
    @GetMapping("/getUser")
    public Object getUserInfo(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        return userService.getUserInfo(userId);
    }
    
    // 用户注销
    @PostMapping("/logout")
    public Object logout(HttpSession session) {
       try{
           session.invalidate();
           return AjaxResult.success("登出成功！");
       }catch (Exception e) {
           return AjaxResult.error(-1,"登出失败，请稍后再试！");
       }
    }

    //删除用户
    @PostMapping("/deleteUser")
    public Object deleteUser(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            return AjaxResult.success(userService.deleteUser(userId), "删除成功！");
        } catch (Exception e) {
            return AjaxResult.error(-1, "删除失败，请稍后再试！");
        }
    }

    //修改密码
    @PostMapping("/updatePassword")
    public Object updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword, HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            return AjaxResult.success(userService.updatePassword(userId, oldPassword, newPassword), "修改成功！");
        } catch (Exception e) {
            return AjaxResult.error(-1, "修改失败，请稍后再试！");
        }
    }
}
